/*
===============================================================================
 Name        : main.c
 Author      : Colin Mcgivern
 Version     :
 Copyright   : Copyright (C)
 Description : Monophonic synthesizer based on the LPCXpresso 1768
			   Selectable waveforms include sine wave, saw-tooth wave
			   and square wave. Includes low pass filter section with
			   cut-off frequency modulation and amplitude envelope.
===============================================================================
*/

#ifdef __USE_CMSIS
#include "LPC17xx.h"
#endif

// includes
#include <stdint.h>
#include <dma.h>
#include <dac.h>
#include <timer.h>
#include <leds.h>
#include <defs.h>
#include <outputbuffer.h>
#include <voice.h>
#include <midi.h>

int main(void) {
	
	// general counter
	int32_t i;

	// init functions
	timer_init();	// init the timer
	DAC_init();		// init digital to analogue converter
	DMA_init();		// init direct memory access controller
	LEDs_init();	// init LEDs
	midi_init();	// init midi
	voice_init();	// init voice

	// output buffers
	int32_t outputBuffer1[bufferSize];
	int32_t outputBuffer2[bufferSize];

	// init output buffers
	outputBuffer_init(&outputBuffer1[0], &outputBuffer2[0]);

	// enter an infinite loop
	while (1) {

		// note control
		midi_check();

		// calculate buffer 1
		for(i = 0; i < bufferSize; i++) {
			outputBuffer1[i] = voice_update();

			// format for DAC
			outputBuffer1[i] = ((outputBuffer1[i] + 512) << 6)// DACR bit 6-15, VALUE
													| 1 << 16;// DACR bit 16, BIAS = 1
		}

		// wait for buffer 2 to finish transfer
		DMA_waitForTransfer();
		timer_disable();

		// transfer output buffer 1
		DMA_config(&outputBuffer1[0]);
		timer_enable();

		// calculate buffer 2
		for(i = 0; i < bufferSize; i++) {
			outputBuffer2[i] = voice_update();

			// format for DAC
			outputBuffer2[i] = ((outputBuffer2[i] + 512) << 6)// DACR bit 6-15, VALUE
													| 1 << 16;// DACR bit 16, BIAS = 1
		}

		// wait for buffer 1 to finish transfer
		DMA_waitForTransfer();
		timer_disable();

		// transfer output buffer 2
		DMA_config(&outputBuffer2[0]);
		timer_enable();
	}
	
	// should never reach here
	return 0 ;
}
